package com.tmptSource.service.impl;

import com.tmpt.dto.Result;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.StringUtils;
import com.tmptSource.bean.OwOffpostRecord;
import com.tmptSource.bean.OwPictureMag;
import com.tmptSource.bean.OwSignin;
import com.tmptSource.dto.OwPictureMagDto;
import com.tmptSource.enums.OwOffpostType;
import com.tmptSource.enums.OwSupportType;
import com.tmptSource.mapper.OwOffpostRecordMapper;
import com.tmptSource.mapper.OwSigninMapper;
import com.tmptSource.mapper.OwWorkPlanMapper;
import com.tmptSource.bean.OwWorkPlan;
import com.tmptSource.dto.OwWorkPlanDto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.service.intf.IOwWorkPlanService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.util.*;

import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value="owWorkPlanService")
@Transactional(propagation = Propagation.REQUIRED)
public class OwWorkPlanService implements IOwWorkPlanService {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired private DataLimitService dataLimitService;
    @Autowired private Mapper mapper;
    @Autowired private MyMapper myMapper;
    @Autowired private MyPageUtils myPageUtils;
    @Autowired
    private OwWorkPlanMapper owWorkPlanMapper;
    @Autowired
    private OwSigninMapper owSigninMapper;
    @Autowired
    private OwOffpostRecordMapper owOffpostRecordMapper;


    @Override
    public Result<OwWorkPlanDto> pagination(OwWorkPlanDto owWorkPlanDto,PageDto pageDto) {
        //分页查询
        Result<OwWorkPlanDto> result = myPageUtils.pagination(
                owWorkPlanDto, pageDto,
                OwWorkPlan.class,
                OwWorkPlanDto.class,
                owWorkPlanMapper,
                false, null);

        /*List<OwWorkPlanDto> owWorkPlanDtoList = (List<OwWorkPlanDto>)result.getResultMap().get("rows");
        for(OwWorkPlanDto owWorkPlanDto1 : owWorkPlanDtoList){
            String outworkerDate = owWorkPlanDto1.getOutworkerDate();
            //查询这一天的签到时间
            OwSignin owSignin = querySigninTimeByDate(outworkerDate);
            log.debug("<======owSignin:"+owSignin.getCreatedate());
            log.debug("<======owSignin:" + owSignin.getId());
        }*/

        return result;
    }

    /**
    * 分布查询，有数据边界控制功能
    * @param owWorkPlanDto
    * @param pageDto
    * @param paramMap
    * @return
    */
    @Override
    public Result<OwWorkPlanDto> pagination(OwWorkPlanDto owWorkPlanDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<OwWorkPlanDto> result = myPageUtils.pagination(
                owWorkPlanDto, pageDto,
                OwWorkPlan.class,
                OwWorkPlanDto.class,
                owWorkPlanMapper,
                paramMap1,
                false, null);

        List<OwWorkPlanDto> owWorkPlanDtoList = (List<OwWorkPlanDto>)result.getResultMap().get("rows");
        for(OwWorkPlanDto owWorkPlanDto1 : owWorkPlanDtoList){
            String outworkerDate = owWorkPlanDto1.getOutworkerDate();
            //查询这一天的签到时间
            OwSignin owSignin = querySigninTimeByDate(outworkerDate,owWorkPlanDto1.getA2userId());
            if(owSignin!=null){
                log.debug("<======owSignin:" + owSignin.getCreatedate() + "  id:" + owSignin.getId());
                owWorkPlanDto1.setSigninTime(DateTool.date2String(owSignin.getCreatedate(), "yyyy-MM-dd HH:mm:ss"));
                owWorkPlanDto1.setSigninLat(owSignin.getLat());
                owWorkPlanDto1.setSigninLng(owSignin.getLng());
                List<OwPictureMag> owPictureMagList = owSignin.getOwPictureMagList();
                List<OwPictureMagDto> owPictureMagDtoList = myMapper.map(owPictureMagList, OwPictureMagDto.class);
                owWorkPlanDto1.setOwPictureMagDtoList(owPictureMagDtoList);
                owWorkPlanDto1.setSignStatus("已签到");
            }else{
                owWorkPlanDto1.setSignStatus("未签到");
            }
            //查询在岗离岗状态
            OwOffpostRecord owOffpostRecord = queryOffpostRecordByDate(outworkerDate, owWorkPlanDto.getA2userId());
            if(owOffpostRecord!=null){
                log.debug("<======owOffpostRecord:" + owOffpostRecord.getCreatedate() + "  id:" + owOffpostRecord.getId());
                String a2userName = owOffpostRecord.getA2userName();
                String owSupportTypeStr = OwSupportType.explain("" + owOffpostRecord.getOwSupportType());
                String owOffpostTypeStr = OwOffpostType.explain("" + owOffpostRecord.getOwOffpostType());
                owWorkPlanDto1.setOffpostA2userName(a2userName);
                owWorkPlanDto1.setOffpostOwOffpostTypeStr(owOffpostTypeStr);
                owWorkPlanDto1.setOffpostOwSupportTypeStr(owSupportTypeStr);
            }

        }
        result.getResultMap().put("rows",owWorkPlanDtoList);

        return result;
    }

    private OwSignin querySigninTimeByDate(String date, String a2userId){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("a2userId",a2userId);
        paramMap.put("dateStart",DateTool.str2Timestamp(date));
        paramMap.put("dateEnd", DateTool.timestampAppend235959999(DateTool.str2Timestamp(date)));
        OwSignin owSignin = owSigninMapper.selectByDate(paramMap);
        return owSignin;
    }

    private OwOffpostRecord queryOffpostRecordByDate(String date, String a2userId){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("a2userId",a2userId);
        paramMap.put("dateStart",DateTool.str2Timestamp(date));
        paramMap.put("dateEnd", DateTool.timestampAppend235959999(DateTool.str2Timestamp(date)));
        OwOffpostRecord owOffpostRecord = owOffpostRecordMapper.selectByDate(paramMap);
        return owOffpostRecord;
    }


    @Override
    public Result<OwWorkPlanDto> selectAll() {
        Result<OwWorkPlanDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);

        List<OwWorkPlan> list = owWorkPlanMapper.selectAll(mapParam);
        List<OwWorkPlanDto> dtoList = myMapper.map(list, OwWorkPlanDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<OwWorkPlanDto> selectById(long id) {
        Result<OwWorkPlanDto> result = new Result();

        OwWorkPlan owWorkPlan = owWorkPlanMapper.selectById(id);
        OwWorkPlanDto dto = mapper.map(owWorkPlan, OwWorkPlanDto.class);
        result.setResultObj(dto);

        return result.success();
    }


    /**
        返回ID值
    */
    @Override
    public Result<OwWorkPlanDto> addData(OwWorkPlanDto owWorkPlanDto){
        Result<OwWorkPlanDto> result = new Result();

        String a2userIdArr = owWorkPlanDto.getA2userId();
        log.debug("=====>a2userIdArr:" + a2userIdArr);
        List<String> a2userIdList = Arrays.asList(a2userIdArr.split(","));
        for(String a2userId : a2userIdList){
            owWorkPlanDto.setA2userId(a2userId);
            //封闭数据
            OwWorkPlan owWorkPlan = mapper.map(owWorkPlanDto, OwWorkPlan.class);
            owWorkPlan.setCreatedate(DateTool.getCurTimestamp());
            //出勤日期
            String outWorkerDateStr = owWorkPlanDto.getStartTime().substring(0,10)+" 00:00:00";
            owWorkPlan.setOutworkerDate(DateTool.str2Timestamp(outWorkerDateStr));
            //查询这个用户当天可排班了，有则更新
            OwWorkPlan owWorkPlan1 = new OwWorkPlan();
            owWorkPlan1.setA2userId(Integer.parseInt(a2userId.trim()));
            owWorkPlan1.setOutworkerDate(DateTool.str2Timestamp(outWorkerDateStr));
            Map<String,Object> paramMap1 = new HashMap<>();
            paramMap1.put("bean", owWorkPlan1);
            List<OwWorkPlan> owWorkPlanList = owWorkPlanMapper.selectAll(paramMap1);
            long i = 0;
            if(owWorkPlanList.size()>0){
                OwWorkPlan owWorkPlan2 = owWorkPlanList.get(0);
                owWorkPlan2.setStartTime(owWorkPlan.getStartTime());
                owWorkPlan2.setEndTime(owWorkPlan.getEndTime());
                owWorkPlan2.setOwWorkType(owWorkPlan.getOwWorkType());
                owWorkPlan2.setOwAreaId(owWorkPlan.getOwAreaId());
                owWorkPlan2.setContent(owWorkPlan.getContent());
                i = owWorkPlanMapper.updateById(owWorkPlan2);
            }else{
                i = owWorkPlanMapper.insert(owWorkPlan);
            }
            if(i==0){
                throw new RuntimeException("插入失败");
            }

        }

        return result.success();
    }

    /**
        返回ID值
    */
    //@Override
    public Result<OwWorkPlanDto> addDataSingle(OwWorkPlanDto owWorkPlanDto){
        Result<OwWorkPlanDto> result = new Result();

        //封闭数据
        OwWorkPlan owWorkPlan = mapper.map(owWorkPlanDto, OwWorkPlan.class);
        owWorkPlan.setCreatedate(DateTool.getCurTimestamp());
        //出勤日期
        String outWorkerDateStr = owWorkPlanDto.getStartTime().substring(0, 10) + " 00:00:00";
        owWorkPlan.setOutworkerDate(DateTool.str2Timestamp(outWorkerDateStr));


        //调用mapper
        long i = owWorkPlanMapper.insert(owWorkPlan);
        if (i ==0){
            return result.fault("插入失败");
        }

        OwWorkPlanDto dto = mapper.map(owWorkPlan, OwWorkPlanDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
        返回ID值
    */
    @Override
    public Result<OwWorkPlanDto> editData(OwWorkPlanDto owWorkPlanDto){
        Result<OwWorkPlanDto> result = new Result();

        String a2userIdArr = owWorkPlanDto.getA2userId();
        log.debug("=====>a2userIdArr:" + a2userIdArr);
        List<String> a2userIdList = Arrays.asList(a2userIdArr.split(","));
        log.debug("=====>a2userIdList.size():" + a2userIdList.size());
        if(a2userIdList.size()>1){
            return result.fault("只能选择一个外勤人员");
        }

        //封装数据
        OwWorkPlan owWorkPlan = mapper.map(owWorkPlanDto, OwWorkPlan.class);
        owWorkPlan.setModifydate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owWorkPlanMapper.updateById(owWorkPlan);
        if(i==0){
            return result.fault("编辑数据失败");
        }

        OwWorkPlanDto dto = mapper.map(owWorkPlan, OwWorkPlanDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
    伪删除记录，返回ID值
    */
    @Override
    public Result deleteById(long id,String adminMan){
        Result result = new Result();

        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("id", id);
        mapParameter.put("modifyman",adminMan);
        mapParameter.put("modifydate",DateTool.getCurTimestamp());

        //调用mapper
        long i = owWorkPlanMapper.deleteById(mapParameter);
        if(i==0){
            return result.fault("删除数据失败");
        }

        return result.success();
    }




    /**
    *页面上查询列的值，动态加载，sql语句读数据库配置而来
    */
    @Override
    public java.util.List select4a2userId(){
        return owWorkPlanMapper.select4a2userId();
    }
    /**
    *页面上查询列的值，动态加载，sql语句读数据库配置而来
    */
    @Override
    public java.util.List select4owAreaId(){
        return owWorkPlanMapper.select4owAreaId();
    }

}
